<?php
namespace app\service;
use think\facade\Db;
use app\model\SupplierModel;
use Exception;

class SupplierService{  
    public function all($params){
        $where=[];
        if(!empty($params['keyword'])){
            $where[] = ['supplier_name','like',"%{$params['keyword']}%"];   
        }
        $datas = SupplierModel::where($where)->select();        
        return $datas;
    } 

    public function list($params){
        $where=[];
        $page = $params['page'];
        $pageCount = $params['page_count'];
        if(!empty($params['keyword'])){
            $where[] = ['supplier_name','like',"%{$params['keyword']}%"];   
        }
        $data = SupplierModel::where($where)->page($page,$pageCount)->order('id','desc')->select(); 
        $count = SupplierModel::where($where)->count(); 
        return ["list"=>$data,"count"=>$count];
    }   

    public function info($id){
        $supplier = SupplierModel::find($id); 
        return $supplier;
    }

    public function save($params){   
        $data = SupplierModel::where('supplier_name',$params['supplier_name'])->find();
                     
        if(empty($params['id'])){
            if($data){
                throw new Exception("供应商已存在");
            }  
            $data = SupplierModel::create($params); 
        }else{
            if($data && $data['id']!=$params['id']){
                throw new Exception("客户已存在");
            }
            $data = SupplierModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = SupplierModel::destroy($params['id']);         
        return $data;
    }
}